from datetime import datetime
from flask import Flask, jsonify, render_template, request, abort
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
app = Flask(__name__)


engine = create_engine('sqlite:///chess.db')
Base = declarative_base()

flag=0

class chess(Base):
    __tablename__ = "chess"
    num=Column(Integer,primary_key=True)
    id = Column(String(100))#当前局势
    act=Column(String(4))#行动   四个数字字符
    count=Column(Integer,server_default='1')#次数  当前局势用这行动的次数
    next_id=Column(String(100)) #行动之后的局势，便于返回
    result=Column(Integer,server_default='0')#结果:0.都没赢   1.红方赢（人）  2.黑方赢(ai) 3.和棋
    def __repr__(self):
        return str(self.num)+' '+str(self.id)+' '+str(self.act)+' '+str(self.count)+' '+str(self.next_id)+' '+str(self.result)

#初始化
@app.route('/reset', methods=["POST"])
def reset():
    flag=request.form.get('reset')
    if flag==0:
        return jsonify({
            'id': '8979695949392919097717866646260600102030405060708012720323436383',
            'flag': 0,
            'result': 0
        })
    else:
        return jsonify({
            'id': '8979695949392919097717866646260600102030405060708012720323436383',
            'flag': 0,
            'result': 0
        })
#动

@app.route('/move', methods=["POST"])
def move():
    id = request.form.get('id')
    act = request.form.get('act')
    flag=request.form.get('flag')
    #这个用于分辨是红方还是黑方
    print(id)
    if id==None or act==None or flag==None:
        return jsonify({
            'error':'接受到错误信息'
        })
    total_list=[]
    active=[]
    for i in range(32):
        total_list.append([int(id[2*i]),int(id[2*i+1])])
    active.append([int(act[0]),int(act[1])])
    active.append([int(act[2]),int(act[3])])
    count=0
    if active[0] in active[1]:
        return ({
            'id': id,
            'flag': flag,
            'result': 0,
            'error':'错误的走法'
        })
    #实现规则
    for x,y in total_list:
        if [x,y] == active[0]:
            if count==0 or count ==8 or count == 16 or count == 24 :#车
                test_count=0
                if x==active[1][0]:
                    if int(y)<int(active[1][1]):
                        for i in range(int(y)+1,int(active[1][1])):
                            for j in total_list:
                                if [x,i] ==j:
                                    test_count+=1
                        if test_count>0:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error':'错误的走法'
                            })
                        else:break
                    else:
                        for i in range(active[1][1]+1,int(y)):
                            for j in total_list:
                                if [x, i] == j:
                                    test_count+=1
                        if test_count>0:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error':'错误的走法'
                            })
                        else :break
                elif y==active[1][1]:
                    if x<active[1][0]:
                        for i in range(x+1,active[1][0]):
                            for j in total_list:
                                if [j,y] ==j:
                                    test_count+=1
                        if test_count>0:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error':'错误的走法'
                            })
                        else:break
                    elif x>active[1][0]:
                        for i in range(active[1][0]+1,x):
                            for j in total_list:
                                if [j,y] ==j:
                                    test_count+=1
                        if test_count>0:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error':'错误的走法'
                            })
                        else:break
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif count==1 or count==7 or count==17 or count==23: #马
                test_count=0
                can_move1=[]#分别对应上下左右
                can_move2=[]
                can_move3=[]
                can_move4=[]
                can_move1.append([int(x)+1,int(y)+2])
                can_move1.append([int(x) - 1, int(y) + 2])
                can_move2.append([int(x) - 1, int(y) - 2])
                can_move2.append([int(x) + 1, int(y) - 2])
                can_move3.append([int(x) + 2, int(y) + 1])
                can_move3.append([int(x) + 2, int(y) - 1])
                can_move4.append([int(x) - 2, int(y) + 1])
                can_move4.append([int(x) - 2, int(y) - 1])

                if [int(active[1][0]),int(active[1][1])] == can_move1[0] or [int(active[1][0]),int(active[1][1])] == can_move1[1]:
                    for i in total_list:
                        if [x,int(y)+1] == i:
                            print('can_move1')
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif [int(active[1][0]),int(active[1][1])] == can_move2[0] or [int(active[1][0]),int(active[1][1])] == can_move2[1]:
                    for i in total_list:
                        if [x, int(y)-1] == i:
                            print('can_move2')
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif [int(active[1][0]),int(active[1][1])] == can_move3[0] or [int(active[1][0]),int(active[1][1])] == can_move3[1]:
                    for i in total_list:
                        if [x+1, int(y) ] == i:
                            print('can_move3')
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move4[0] or [int(active[1][0]), int(active[1][1])] == can_move4[1]:
                    for i in total_list:
                        if [x-1, int(y)] == i:
                            print('can_move4')
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                else:
                    print(active)
                    print(can_move1)
                    print(can_move2)
                    print(can_move3)
                    print(can_move4)
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif count==2 or count==6 or count==18 or count==22: #象
                can_move1=[]
                can_move2=[]
                can_move3=[]
                can_move4=[]
                flag1=0
                flag2=0
                flag3=0
                flag4=0
                if x<8 and (y<4 or 4<y<9):
                    can_move1=[int(x)+2,int(y)+2]
                if x>0 and (y<4 or 4<y<9) :
                    can_move2=[int(x)-2,int(y)+2]
                if x>0 and (0<y<5 or y>5):
                    can_move3=[int(x)-2,int(y)-2]
                if x<8 and (0<y<5 or y>5):
                    can_move4=[int(x) + 2, int(y) - 2]
                print(can_move1)
                print(can_move2)
                print(can_move3)
                print(can_move4)
                if active[1] == can_move1:
                    for i in total_list:
                        if [int(x)+1,int(y)+1] == i:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif active[1] == can_move2:
                    for i in total_list:
                        if [int(x) - 1, int(y) + 1] == i:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif active[1] == can_move3:
                    for i in total_list:
                        if [int(x)-1,int(y)-1] == i:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                elif active[1] == can_move4:
                    for i in total_list:
                        if [int(x) + 1, int(y) - 1] == i:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    break
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif count==3 or count==5 or count==19 or count==21: #士
                can_move1 = []
                can_move2 = []
                can_move3 = []
                can_move4 = []
                if ((int(y)) < 2 and (int(x))<5) or (6< (int(y)) < 9 and (int(x))<5):
                    can_move1=[int(x) + 1, int(y) + 1]
                if ((int(y)) < 2 and (int(x))>3) or (6< (int(y)) < 9 and (int(x))>3):
                    can_move2=[int(x) - 1, int(y) + 1]
                if ((int(y)) >0  and (int(x))>3) or ( (int(y)) >6 and (int(x))>3):
                    can_move3=[int(x) - 1, int(y) - 1]
                if ((int(y)) >0 and (int(x))<5) or ( (int(y)) >6 and (int(x))<5):
                    can_move4=[int(x) + 1, int(y) - 1]
                if [int(active[1][0]), int(active[1][1])] == can_move1:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move2:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move3:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move4:
                    break
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif count==4 or count==20:#将
                can_move1 = []
                can_move2 = []
                can_move3 = []
                can_move4 = []
                can_move5 = []
                if int(x)<5:
                    can_move1=[int(x) + 1, int(y)]
                if int(x)>3:
                    can_move2=[int(x) - 1, int(y)]
                if 6<int(y)<9 or int(y)<3:
                    can_move3=[int(x) , int(y)+1]
                if int(y)>7 or int(y)>0:
                    can_move4=[int(x) , int(y)-1]
                test_count=0#路径上的棋子数量
                cal_count=0#计数器
                check_count=0
                for [i,j] in total_list:
                    if i==active[0][0] and j!=active[0][1] and (active[0][1]<=j<=active[1][1] or active[1][1]<= j <=active[0][1]):
                        if [i,j] == active[1]:
                            checkcount=cal_count
                        test_count+=1
                    cal_count+=1
                if test_count==1 and (checkcount==4 or checkcount==20):
                    can_move5=active[1]
                if [int(active[1][0]), int(active[1][1])] == can_move1:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move2:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move3:
                    break
                elif [int(active[1][0]), int(active[1][1])] == can_move4:
                    break
                elif active[1] == can_move5 and test_count==1:
                    break
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif count==9 or count==10 or count==25 or count==26: #炮
                test_count=0
                check=0
                if active[1][0]==active[0][0] or active[1][1]==active[0][1]:
                    if active[1][0] == active[0][0]:
                        if active[0][1]>active[1][1]:
                            for hi in range(active[1][1]+1,active[0][1]):
                                for i in total_list:
                                    if [active[0][0],hi] ==i:
                                        test_count+=1
                                    if active[1]==i:
                                        check=1
                            if test_count==1 and check==1:
                                break
                            elif test_count==0 and check==0:
                                break
                            else :
                                print(test_count)
                                print(check)
                                return jsonify({
                                    'id': id,
                                    'flag': flag,
                                    'result': 0,
                                    'error': '错误的走法'
                                })
                        elif active[0][1]<active[1][1]:
                            for hi in range(active[0][1]+1,active[1][1]):
                                for i in total_list:
                                    if [active[0][0],hi] ==i:
                                        test_count+=1
                                    if active[1] == i:
                                        check = 1
                            if test_count==1 and check==1:
                                break
                            elif test_count==0 and check==0:
                                break
                            else:
                                return jsonify({
                                    'id': id,
                                    'flag': flag,
                                    'result': 0,
                                    'error': '错误的走法'
                                })
                        else:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                    elif active[1][1] == active[0][1]:
                        if active[0][0]>active[1][0]:
                            for i in range(active[1][0]+1,active[0][0]):
                                for hi in total_list:
                                    if [i,active[0][1]] == hi:
                                        test_count+=1
                                    if active[1]==hi:
                                        check=1
                            if test_count==1 and check==1:
                                break
                            elif test_count==0 and check==0:
                                break
                            else :
                                return jsonify({
                                    'id': id,
                                    'flag': flag,
                                    'result': 0,
                                    'error': '错误的走法'
                                })
                        elif active[0][0]<active[1][0]:
                            for i in range(active[0][0]+1,active[1][0]):
                                for hi in total_list:
                                    if [i,active[0][1]] ==hi:
                                        test_count+=1
                                    if active[1]==hi:
                                        check=1
                            if test_count==1 and check==1:
                                break
                            elif test_count==0 and check==0:
                                break
                            else:
                                print(active)
                                print(test_count)
                                print(check)
                                return jsonify({
                                    'id': id,
                                    'flag': flag,
                                    'result': 0,
                                    'error': '错误的走法'
                                })
                        else:
                            return jsonify({
                                'id': id,
                                'flag': flag,
                                'result': 0,
                                'error': '错误的走法'
                            })
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
            elif 10<count<16 or 26<count <32:#卒
                can_move1=[]
                can_move2=[]
                can_move3=[]
                if 10<count<16:
                    if y>4:
                        can_move1=[x,y-1]
                    elif y<5:
                        can_move1=[x,y-1]
                        can_move2=[x-1,y]
                        can_move3=[x+1,y]
                    if active[1] == can_move1:
                        break
                    elif active[1] == can_move2:
                        break
                    elif active[1] == can_move3:
                        break
                    else:
                        return jsonify({
                            'id': id,
                            'flag': flag,
                            'result': 0,
                            'error': '错误的走法'
                        })
                if 26<count<32:
                    if y<5:
                        can_move1=[x,y+1]
                    elif y>4:
                        can_move1=[x,y+1]
                        can_move2=[x-1,y]
                        can_move3=[x+1,y]
                    if active[1] == can_move1:
                        break
                    elif active[1] == can_move2:
                        break
                    elif active[1] == can_move3:
                        break
                    else:
                        return jsonify({
                            'id': id,
                            'flag': flag,
                            'result': 0,
                            'error': '错误的走法'
                        })
                else:
                    return jsonify({
                        'id': id,
                        'flag': flag,
                        'result': 0,
                        'error': '错误的走法'
                    })
        count+=1
    session = Session()
    chesscount = 0
    result = 0
    nextid = ''
    for x, y in total_list:
        if [x, y] == active[1]:
            total_list[chesscount] = [9, 9]
            if chesscount == 4:
                result = 2
            elif chesscount == 20:
                result = 1
        if [x, y] == active[0]:
            total_list[chesscount] = active[1]
        chesscount += 1
    for [x, y] in total_list:
        nextid += str(x)
        nextid += str(y)
    test = session.query(chess).filter(chess.id == nextid).all()
    print(test)
    if flag=='0' and test != []:
        check_next=session.query(chess).filter(chess.id == nextid).order_by(chess.count.desc()).first()
        return jsonify({
            'id':check_next.next_id,
            'flag':0,
            'result':check_next.result,
            'act':check_next.act
        })
    elif flag=='0':
        return jsonify({
            'id':nextid,
            'flag':1,
            'result':result
        })
    elif flag=='1':
        session = Session()
        newchess = chess(id=id, act=act,next_id=nextid,result=result)
        session.add(newchess)
        session.commit()
        return jsonify({
            'id': nextid,
            'flag': 0,
            'result': result
        })
if __name__ == '__main__':
    Base.metadata.drop_all(engine)#清理数据库
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    app.run()
